﻿using Microsoft.Extensions.Options;
using OnWork.Admin.DAL.System;
using OnWork.Admin.Util.Configs;
using System.Collections.Concurrent;

namespace OnWork.Admin.DAL
{
    /// <summary>
    /// 全部数据库对象
    /// </summary>
    public class DBManage : ISingleton
    {
        private readonly List<ConnectionConfiguration> _connections;

        /// <summary>
        /// 连接配置
        /// </summary>
        /// <param name="connections"></param>
        public DBManage(IOptions<List<ConnectionConfiguration>> connections)
        {
            _connections = connections.Value;
        }

        /// <summary>
        /// 数据中心库
        /// </summary>
        public SqlSugarScope System
        {
            get
            {
                return GetDbScope(nameof(System), db =>
                {
                    //数据库不存在 则创建
                    db.DbMaintenance.CreateDatabase();

                    Type[] types = typeof(DemoEntity).Assembly.GetTypes()
                    .Where(it => it.IsClass && it.FullName.Contains("OnWork.Admin.DAL.System"))//命名空间过滤，当然你也可以写其他条件过滤
                    .ToArray();
                    db.CodeFirst.SetStringDefaultLength(200).InitTables(types);//根据types创建表

                    ////初始化表结构
                    //db.CodeFirst.SetStringDefaultLength(200).InitTables(typeof(DataDictionary));
                    //db.CodeFirst.SetStringDefaultLength(200).InitTables(typeof(ItemType));
                    //db.CodeFirst.SetStringDefaultLength(200).InitTables(typeof(ItemConfig));
                    ////操作配置
                    //db.CodeFirst.SetStringDefaultLength(200).InitTables(typeof(ItemOperate));
                    //db.CodeFirst.SetStringDefaultLength(200).InitTables(typeof(OperateSendText));
                    ////条件配置
                    //db.CodeFirst.SetStringDefaultLength(200).InitTables(typeof(ItemTrigger));
                    //db.CodeFirst.SetStringDefaultLength(200).InitTables(typeof(TriggerFastMenu));

                    //db.CodeFirst.InitTables(typeof(BanWordPO));
                });
            }
        }

        /// <summary>
        /// 获取数据库连接
        /// </summary>
        /// <param name="name">数据连接名称</param>
        private SqlSugarScope GetDbScope(string name, Action<SqlSugarScope>? init = null)
        {
            //如果字典包含则直接返回
            if (DictSqlSugarScope.ContainsKey(name))
            {
                var sql = DictSqlSugarScope[name];
                if (sql != null)
                {
                    return sql;
                }
            }

            //获取当前连接
            var current = _connections.Where(x => x.Name == name).First();

            if (current != null)
            {
                var db = GetSqlSugarScope(current, name);

                if (init != null)
                {
                    init.Invoke(db);
                }

                return db;
            }

            throw new FileNotFoundException($"{name}没有在配置文件中找到");

            ////默认使用SqlLite
            //var path = AppContext.BaseDirectory.Replace(@"\bin\Debug\net6.0", "");//获取具体路径
            //var ConnectionString = @"DataSource=" + path + @"\DataBase\DataCenter.sqlite";

            //return GetSqlSugarScope(DbType.Sqlite, ConnectionString, name);
        }

        /// <summary>
        /// 静态字典
        /// </summary>
        private static ConcurrentDictionary<string, SqlSugarScope> DictSqlSugarScope = new ConcurrentDictionary<string, SqlSugarScope>();

        /// <summary>
        /// 获取对象
        /// </summary>
        /// <param name="dbType"></param>
        /// <param name="connStr"></param>
        /// <param name="dictKey">关键数据库Key</param>
        /// <returns></returns>
        private static SqlSugarScope GetSqlSugarScope(ConnectionConfiguration connConfig, string dictKey)
        {
            ////如果字典包含则直接返回
            //if (DictSqlSugarScope.ContainsKey(dictKey))
            //{
            //    var sql = DictSqlSugarScope[dictKey];
            //    if (sql != null)
            //    {
            //        return sql;
            //    }
            //}

            if (!string.IsNullOrEmpty(connConfig.ConnectionString))
            {
                //创建数据库对象
                var conn = new ConnectionConfig()
                {
                    ConnectionString = connConfig.ConnectionString,
                    DbType = connConfig.DbType,
                    IsAutoCloseConnection = connConfig.IsAutoCloseConnection
                };

                //根据数据库的规范修改表名,字段名
                if (connConfig.IsToUnderLine)
                {
                    conn.ConfigureExternalServices = new ConfigureExternalServices()
                    {
                        EntityService = (x, p) => //处理列名
                        {
                            //要排除DTO类，不然MergeTable会有问题
                            p.DbColumnName = UtilMethods.ToUnderLine(p.DbColumnName);//ToUnderLine驼峰转下划线方法
                        },
                        EntityNameService = (x, p) => //处理表名
                        {
                            //最好排除DTO类
                            p.DbTableName = UtilMethods.ToUnderLine(p.DbTableName);//ToUnderLine驼峰转下划线方法
                        }
                    };
                }
                SqlSugarScope db = new SqlSugarScope(conn);
                DictSqlSugarScope[dictKey] = db;
                return db;
            }

            return null;
        }
    }
}